package yuan.deng.controller;

import com.github.pagehelper.PageInfo;
import org.apache.commons.beanutils.BeanUtils;
import yuan.deng.domain.store.Dept;
import yuan.deng.service.impl.store.DeptServiceImpl;
import yuan.deng.service.store.DeptService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@WebServlet("/system/dept/*")
public class DeptServlet extends BaseServlet {
    private DeptService deptService=new DeptServiceImpl();

    protected void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String page = req.getParameter("page");
        //调用查询所有方法
        List<Dept> list = deptService.findAll(page);
        //发松到前端
        System.out.println(list);
        PageInfo<Dept> pageInfo=new PageInfo<>(list);
        System.out.println(list.toString());

        req.setAttribute("page",pageInfo);

        req.getRequestDispatcher("/pages/dept/list.jsp").forward(req,resp);
    }
    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, String[]> map = req.getParameterMap();
        Dept c=new Dept();
        try {
            BeanUtils.populate(c,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        String id = UUID.randomUUID().toString().replace(" ", "-");
        c.setId(id);
        deptService.save(c);

        findAll(req,resp);
    }
    protected void findById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        Dept company = deptService.findById(id);
        req.setAttribute("company",company);
        req.getRequestDispatcher("/pages/company/update.jsp").forward(req,resp);
    }
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, String[]> map = req.getParameterMap();
        Dept company=new Dept();
        try {
            BeanUtils.populate(company,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        deptService.update(company);
        findAll(req,resp);
    }
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        String[] strings = id.split(",");
        deptService.delete(strings);
        findAll(req,resp);
    }
}
